<!-- pages/login.vue -->
<template>
  <div class="login-container">
    <a-card title="用户登录" class="login-card">
      <a-form :model="form" :rules="rules" @finish="handleLogin" class="login-form">
        <a-form-item name="username">
          <a-input v-model:value="form.username" placeholder="用户名" size="large">
            <template #prefix>
              <UserOutlined />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item name="email">
          <a-input v-model:value="form.email" placeholder="邮箱" size="large">
            <template #prefix>
              <MailOutlined />
            </template>
          </a-input>
        </a-form-item>

        <a-form-item name="password">
          <a-input-password v-model:value="form.password" placeholder="密码" size="large">
            <template #prefix>
              <LockOutlined />
            </template>
          </a-input-password>
        </a-form-item>

        <a-form-item>
          <a-button type="primary" html-type="submit" size="large" :loading="loading" block>
            {{ loading ? '登录中...' : '登录' }}
          </a-button>
        </a-form-item>

        <div class="login-options">
          <a-checkbox v-model:checked="rememberMe">记住我</a-checkbox>
          <a class="forgot-link" @click="navigateTo('/forgot-password')">忘记密码？</a>
        </div>
      </a-form>

      <div class="register-link">
        还没有账号？<a class="register-now" @click="navigateTo('/register')">立即注册</a>
      </div>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { message } from 'ant-design-vue'
import type { Rule } from 'ant-design-vue/es/form'
import { UserOutlined, MailOutlined, LockOutlined } from '@ant-design/icons-vue'

const authStore = useAuthStore()

interface LoginForm {
  email: string
  password: string
  username: string
}

const form = reactive<LoginForm>({
  email: '',
  password: '',
  username: ''
})

const loading = ref(false)
const rememberMe = ref(false)

// 表单验证规则
const rules: Record<string, Rule[]> = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度为2-20个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少为6位', trigger: 'blur' }
  ]
}

const handleLogin = async () => {
  loading.value = true

  try {
    const response = await $fetch('/api/auth/login', {
      method: 'POST',
      body: form
    })

    console.log("登录成功响应:", response)

    if (response && response.data) {
      const { token, user } = response.data

      if (token && user) {
        // 存储 token 和用户信息到 Pinia store
        authStore.setToken(token)
        authStore.setUser({
          id: user.id,
          username: user.username,
          email: user.email
          // 不存储密码
        })

        message.success('登录成功！')

        // 延迟跳转，让用户看到成功消息
        setTimeout(() => {
          navigateTo('/')
        }, 1000)
      } else {
        message.warning('登录成功，但未返回token或用户信息')
      }
    } else {
      message.error('响应格式错误')
    }

  } catch (error: any) {
    console.error("登录错误:", error)

    const status = error.status
    if (status === 401) {
      message.error('邮箱或密码错误')
    } else if (status === 404) {
      message.error('用户不存在，请先注册')
    } else if (status === 422) {
      message.error('请求参数错误，请检查输入')
    } else if (status >= 500) {
      message.error('服务器错误，请稍后重试')
    } else {
      message.error('登录失败')
    }
  } finally {
    loading.value = false
  }
}

// 页面加载时检查是否已登录
onMounted(() => {
  if (authStore.isAuthenticated) {
    console.log('检测到已登录，用户:', authStore.currentUser)
    // 可以选择自动跳转或显示提示
    // navigateTo('/')
  }
})
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.login-card {
  width: 100%;
  max-width: 400px;
}

.login-form {
  margin-bottom: 20px;
}

.login-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.forgot-link {
  color: #1890ff;
  cursor: pointer;
}

.forgot-link:hover {
  text-decoration: underline;
}

.register-link {
  text-align: center;
  margin-top: 20px;
  color: #666;
}

.register-link a {
  color: #1890ff;
  cursor: pointer;
}

.register-link a:hover {
  text-decoration: underline;
}
</style>